//引入模块
const express = require("express");
const query = require("../util/query.js");
const Token = require('../util/token.js');

//创建空路由器
let router = express.Router();
//挂载路由
//1.6. 收货地址管理
//===============================================
//1.6.1 保存收货地址保存收货地址
// 参数名	参数说明	备注
// id	可选参数，如果有id表示做编辑操作，如果没有id参数表示做新增操作
// name 姓名
// tel 电话
// province 省份
// city 城市
// county 区县
// area_code 地区编码，通过省市区选择获取（必填）
// postal_code 邮政编码
// address_detail 详细地址
// is_default 是否选择默认0 | 1
router.post("/save", async (req, res) => {
    //判断用户是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //获取数据
        let {id, name, tel, province, city, county, area_code, postal_code, address_detail, is_default} = req.body;
        id = parseInt(id);

        if (!name) throw("收货人姓名不能为空");
        if (!tel) throw("收货人手机号不能为空");
        if (!address_detail) throw("详细地址不能为空");

        let user_id = user.id;
        let address = {user_id, name, tel, province, city, county, area_code, postal_code, address_detail, is_default};


        if (id) {
            let sql = `select * from user_address where id = ${id}`;
            let result = await query(sql);
            if (result.length == 0) throw("记录不存在");

            sql = "UPDATE user_address SET ? WHERE id=?";
            result = await query(sql, [address, id]);
            //如果数据更改成功，响应对象
            if (result.affectedRows > 0) res.send({code: 1, msg: "更改成功", data: {id}});
            else throw("更改失败")

        } else {
            let sql = "INSERT INTO user_address SET ?";
            let result = await query(sql, [address]);
            res.send({code: 1, msg: "保存成功", data: {id: result.insertId}});
        }
    } catch (error) {
        res.send({code: -1, msg: "Query异常,error:" + error});
        return;
    }
});

//===============================================
//1.6.2 查询收货地址列表 address
router.get("/list", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //执行SQL语句 ,返回当前登录用户的地址列表
        let sql = `select * from v_user_address where user_id =${user.id} `;
        let result = await query(sql);
        let data = result;
        res.send({code: 1, msg: "获取成功", data});
    } catch (error) {
        res.send({code: -1, msg: `获取失败, error: ${error}`}); //throw err;
    }
});

//===============================================
//1.6.3查询需要修改的收货地址信息 address/edit
// 参数名	参数说明	备注
// id	收货地址id
router.get("/detail", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //1获取数据
        let id = parseInt(req.query.id);
        //验证数据
        let sql = `select * from v_user_address where user_id = ${user.id} AND id = ${id}`;
        if (!id) {
            sql = `select * from v_user_address where user_id = ${user.id} limit 1`;
        }
        //执行SQL语句
        let result = await query(sql);
        let data = result[0];  //只有对应的1条数据
        res.send({code: 1, msg: "获取成功", data});
    } catch (error) {
        res.send({code: -1, msg: `获取失败, error: ${error}`}); //throw err;
    }
});


//===============================================
//1.6.4 根据id删除收货地址
// 参数名	参数说明	备注
// id	收货地址id
router.post("/delete", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //1获取数据
        let id = parseInt(req.body.id);
        //验证数据
        if (!id) throw("收货地址id不能为空");

        //执行SQL语句
        let sql = `delete from user_address where user_id = ${user.id} AND id = ${id}`;
        await query(sql);
        res.send({code: 1, msg: "删除成功"});
    } catch (error) {
        res.send({code: -1, msg: `删除失败, error: ${error}`}); //throw err;
    }
});

//===============================================
//1.6.5 获取默认的收货地址
// 参数名	 参数说明
// id	    可选参数，如果传递了id就获取id对应的收货地址，
//        如果没有传递id就获取默认的收货地址
router.get("/default", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //1获取数据
        let id = req.query.id;
        //2验证数据
        //3 执行SQL语句
        let sql;
        if (undefined == id) {
            sql = `select * from v_user_address where user_id = ${user.id} ORDER BY is_default DESC,id DESC LIMIT 1`;
        } else {
            sql = `select * from v_user_address where user_id = ${user.id} AND id = ${id}`;
        }
        //console.log(sql);

        let result = await query(sql);
        let data = result;
        res.send({code: 1, msg: "获取成功", data});

    } catch (error) {
        res.send({code: -1, msg: `获取失败, error: ${error}`}); //throw err;
    }
});

//===============================================
//导出路由器
module.exports = router;
